package com.javasm.crm.service.b2cReturns.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasm.crm.domin.criteria.B2cReturnsApplyCriteria;
import com.javasm.crm.domin.entity.aftersale.Inorder;
import com.javasm.crm.domin.entity.b2cReturns.B2creturnsapply;
import com.javasm.crm.domin.entity.b2cReturns.B2creturnsapplygood;
import com.javasm.crm.domin.vo.B2creturnsapplyVO;
import com.javasm.crm.mapper.aftersale.InorderMapper;
import com.javasm.crm.mapper.b2cReturns.B2creturnsapplyMapper;
import com.javasm.crm.service.b2cReturns.B2cReturnsApplyGoodService;
import com.javasm.crm.service.b2cReturns.B2cReturnsApplyService;
import com.javasm.crm.utils.page.PageResult;
import com.javasm.crm.utils.transfer.B2cReturnsApplyTransfer;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wxl
 * @since 2021-07-12
 */
@Service
@Transactional
@RequiredArgsConstructor
public class B2cReturnsApplyServiceImpl extends ServiceImpl<B2creturnsapplyMapper, B2creturnsapply> implements B2cReturnsApplyService {

    private final B2creturnsapplyMapper applyMapper;
    private final B2cReturnsApplyTransfer applyTransfer;
    private final B2cReturnsApplyGoodService b2cReturnsApplyGoodService;
    private final InorderMapper inorderMapper;

    /**
     * 分页，条件模糊查询
     * @param applyCriteria 查询条件
     * @return 分页查询结果
     */
    @Override
    public PageResult<B2creturnsapply> searchPageByCriteria(B2cReturnsApplyCriteria applyCriteria) {

        //当前页和每页条数
        Integer currentPage = applyCriteria.getCurrentPage();
        Integer pageSize = applyCriteria.getPageSize();
        if ("".equals(currentPage) || currentPage==null){
            currentPage =1;
        }
        if ("".equals(pageSize) || pageSize==null){
            pageSize = 5;
        }
        PageHelper.startPage(currentPage,pageSize);

        QueryWrapper<B2creturnsapply> applyQueryWrapper = new QueryWrapper<B2creturnsapply>();
        LambdaQueryWrapper<B2creturnsapply> lambda = applyQueryWrapper.lambda();
        //查询条件拼接
        //申请单创建时间
        LocalDateTime startTime = applyCriteria.getStartTime();
        LocalDateTime endTime = applyCriteria.getEndTime();
        if (startTime!=null &&endTime != null){
            lambda.between(B2creturnsapply::getCreateTime,startTime,endTime);
        }

        //申请单审批时间
        LocalDateTime approvalStartTime = applyCriteria.getApprovalStartTime();
        LocalDateTime approvalEndTime = applyCriteria.getApprovalEndTime();
        if (approvalStartTime!=null &&approvalEndTime != null){
            lambda.between(B2creturnsapply::getApprovalTime,approvalStartTime,approvalEndTime);
        }

         //订单编号
         String sellCode = applyCriteria.getSellCode();
        if (StringUtils.hasText(sellCode)){
            lambda.like(B2creturnsapply::getSellCode, sellCode);
        }


        // 投诉单号
        Integer complaintId = applyCriteria.getComplaintId();
        if (!"".equals(complaintId) && complaintId!=null){
            lambda.like(B2creturnsapply::getComplaintId, complaintId);
        }

        //制单人
        String producer=applyCriteria.getProducer();
        if (StringUtils.hasText(producer)){
            lambda.like(B2creturnsapply::getProducer, producer);
        }

        //审批人
        String approver=applyCriteria.getApprover();
        if (StringUtils.hasText(approver)){
            lambda.like(B2creturnsapply::getApprover, approver);
        }

        //审批状态
       Integer approvalStatus = applyCriteria.getApprovalStatus();
        if (!"".equals(approvalStatus) && approvalStatus!=null){
            lambda.eq(B2creturnsapply::getApprovalStatus, approvalStatus);
        }
        //单据状态
        lambda.eq(B2creturnsapply::getStatus, 0);

        //查询
        List<B2creturnsapply> b2creturnsapplies = applyMapper.selectList(applyQueryWrapper);
        PageInfo<B2creturnsapply> applyPageInfo = new PageInfo<>(b2creturnsapplies);
        long total = applyPageInfo.getTotal();



        return new PageResult<>(total,b2creturnsapplies);
    }

    /**
     * 申请单详情查看
     * @param applyId 申请单编号
     * @return 申请单详情
     */
    @Override
    public B2creturnsapplyVO searchDetailByApplyId(String applyId) {

        QueryWrapper<B2creturnsapply> applyQueryWrapper = new QueryWrapper<B2creturnsapply>();
        LambdaQueryWrapper<B2creturnsapply> lambda = applyQueryWrapper.lambda();
        if (StringUtils.hasText(applyId)){
            lambda.eq(B2creturnsapply::getApplyId, applyId);
        }
        B2creturnsapply b2creturnsapply = applyMapper.selectOne(applyQueryWrapper);
        B2creturnsapplyVO b2creturnsapplyVO = applyTransfer.toVO(b2creturnsapply);

        QueryWrapper<B2creturnsapplygood> applyGoodQueryWrapper = new QueryWrapper<B2creturnsapplygood>();
        LambdaQueryWrapper<B2creturnsapplygood> lambdaGood = applyGoodQueryWrapper.lambda();
        if (StringUtils.hasText(applyId)){
            lambdaGood.eq(B2creturnsapplygood::getApplyId, applyId);
        }
        lambdaGood.eq(B2creturnsapplygood::getNewId, "0");
        List<B2creturnsapplygood> list = b2cReturnsApplyGoodService.list(applyGoodQueryWrapper);

        lambdaGood.clear();
        if (StringUtils.hasText(applyId)){
            lambdaGood.eq(B2creturnsapplygood::getApplyId, applyId);
        }
        lambdaGood.ne(B2creturnsapplygood::getNewId, "0");

        List<B2creturnsapplygood> listNew = b2cReturnsApplyGoodService.list(applyGoodQueryWrapper);

        b2creturnsapplyVO.setList(list);
        b2creturnsapplyVO.setListNew(listNew);

        return b2creturnsapplyVO;
    }


    /**
     * 新增申请单
     * @param b2creturnsapplyVO 申请单
     * @return 添加结果
     */
    @Override
    public Integer saveApply(B2creturnsapplyVO b2creturnsapplyVO){
        B2creturnsapply b2creturnsapply = applyTransfer.toEntity(b2creturnsapplyVO);
        LocalDateTime dateTime = LocalDateTime.now();
        b2creturnsapply.setCreateTime(dateTime);
        int num = applyMapper.insert(b2creturnsapply);
        if (num == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  num;
        }
        Integer id = b2creturnsapply.getId();
        String applyId = "apply" + id.toString();
        b2creturnsapply.setApplyId(applyId);
        num =applyMapper.updateById(b2creturnsapply);
        if (num == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  num;
        }
        for (B2creturnsapplygood b2creturnsapplygood : b2creturnsapplyVO.getList()) {
            b2creturnsapplygood.setApplyId(applyId);
            boolean save = b2cReturnsApplyGoodService.save(b2creturnsapplygood);
            if (!save){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  0;
            }
        }
        for (B2creturnsapplygood b2creturnsapplygood : b2creturnsapplyVO.getListNew()) {
            b2creturnsapplygood.setApplyId(applyId);
            boolean save = b2cReturnsApplyGoodService.save(b2creturnsapplygood);
            if (!save){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  0;
            }
        }
        return num;
    }

    /**
     * 删除退换单，经过审批的只修改状态
     * @param b2creturnsapply 要删除的申请单
     * @return 删除结果
     */
    @Override
    public Integer deleteApply(B2creturnsapply b2creturnsapply) {
        String applyId = b2creturnsapply.getApplyId();
        if(!StringUtils.hasText(applyId)){
            return 0;
        }
        QueryWrapper<B2creturnsapply> applyQueryWrapper = new QueryWrapper<B2creturnsapply>();
        LambdaQueryWrapper<B2creturnsapply> lambda = applyQueryWrapper.lambda();
        lambda.eq(B2creturnsapply::getApplyId,applyId);
        b2creturnsapply = applyMapper.selectOne(applyQueryWrapper);
        int delete;
        if(b2creturnsapply.getApprovalStatus()==0){
            delete = applyMapper.delete(applyQueryWrapper);
            if(delete>0){
                delete = b2cReturnsApplyGoodService.deleteByApplyId(applyId);
            }
        }else {
            b2creturnsapply.setStatus(1);
            delete = applyMapper.updateById(b2creturnsapply);
        }
        return delete;
    }

    /**
     * 修改申请单
     * @param b2creturnsapplyVO 修改后的申请单
     * @return 修改结果
     */
    @Override
    public Integer updateApply(B2creturnsapplyVO b2creturnsapplyVO) {
        if(b2creturnsapplyVO.getApprovalStatus()==1){
            return 0;
        }
        B2creturnsapply b2creturnsapply = applyTransfer.toEntity(b2creturnsapplyVO);
        int update = applyMapper.updateById(b2creturnsapply);
        if (update == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  update;
        }
        b2cReturnsApplyGoodService.deleteByApplyId(b2creturnsapply.getApplyId());
        for (B2creturnsapplygood b2creturnsapplygood : b2creturnsapplyVO.getList()) {
            b2creturnsapplygood.setApplyId(b2creturnsapply.getApplyId());
            boolean b = b2cReturnsApplyGoodService.save(b2creturnsapplygood);
            if(!b){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  0;
            }
        }
        for (B2creturnsapplygood b2creturnsapplygood : b2creturnsapplyVO.getListNew()) {
            b2creturnsapplygood.setApplyId(b2creturnsapply.getApplyId());
            boolean save = b2cReturnsApplyGoodService.save(b2creturnsapplygood);
            if (!save){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  0;
            }
        }
        return update;
    }

    /**
     * 申请单审批
     * @param b2creturnsapply 审批后的申请单
     * @return 审批结果
     */
    @Override
    public Integer approvalApply(B2creturnsapply b2creturnsapply) {
        LocalDateTime dateTime = LocalDateTime.now();
        b2creturnsapply.setApprovalTime(dateTime);
        int update = applyMapper.updateById(b2creturnsapply);
        return update;
    }

    /**
     * 批量删除
     * @param applyIdList 要删除的申请单
     * @return 删除结果
     */
    @Override
    public Integer deleteApplys(List<Serializable> applyIdList) {
        int delete = 0;
        for (Serializable serializable : applyIdList) {
            B2creturnsapply b2creturnsapply = new B2creturnsapply();
            b2creturnsapply.setApplyId(serializable.toString());
            delete += deleteApply(b2creturnsapply);
        }
        return delete;
    }

    /**
     * 批量生成入库订单
     * @param applyList 申请单列表
     * @return 结果
     */
    @Override
    public Integer applyToInorder(List<B2creturnsapply> applyList) {
        int insert = 0;
        Inorder inorder = new Inorder();
        inorder.setCreateTime(LocalDateTime.now());
        inorder.setStatus(0);
        inorder.setType(2);
        for (B2creturnsapply apply : applyList) {
            inorder.setApplyCode(apply.getApplyId());
            inorder.setCreateBy(apply.getProducer());
            int success = inorderMapper.insert(inorder);
            if(success>0){
                String inorderId = "applyInorder" + inorder.getId().toString();
                inorder.setInorderCode(inorderId);
                inorderMapper.updateById(inorder);
                apply.setApprovalStatus(3);
                apply.setEntryId(inorderId);
                insert += applyMapper.updateById(apply);
            }
        }
        return insert;
    }


}
